import Router from 'vue-router';
import {Flatten} from '../utils/common';
import router, {asyncRouterMap} from '../router';

//递归循环,判断 parentId与id,获取子级菜单并排序
const filter = (data, list) => {
  list.forEach(item => {
    item.children = [];
    for (let j = 0; j < data.length; j++) {
      if (data[j].parentId === item.id) {
        item.children.push(data[j]);
      }
      else {
        if (item.children) {
          filter(data, item.children)
        }
      }
    }
    if (item.children.length === 0) {
      delete item.children;
    }
  });
  return list.sort(compare('sort'));
};
//数组排序
const compare = (property) => {
  return function (a, b) {
    let value1 = a[property];
    let value2 = b[property];
    return value1 - value2;
  }
};

//退出登录
export function logout({commit}) {
  return commit('LOGOUT');
}

//初始化页签,当前路由,导航菜单
export function initMenus({commit, state}) {
  return new Promise((resolve) => {
    const Path = router.history.current;//当前路由
    let List = [];//Index下所有的子路由
    router.options.routes.forEach(item => {
      if (Array.isArray(item.children) && item.path === state.index) {
        List = item.children;
      }
    });
    const Nav = Flatten(JSON.parse(JSON.stringify(state.list)), 'children', true);
    const Parent = Nav.map(v => v.parentId);
    const Menus = [];//导航栏路由列表
    //将所有的导航菜单转化为一维数组,保留需要的属性,并根据登录过滤导航权限
    List.filter(v => v.meta.bar).forEach(item => {
      for (let i = 0; i < Nav.length; i++) {
        if (item.path === Nav[i].path) {
          Menus.push({
            id: Nav[i].id,
            parentId: Nav[i].parentId,
            icon: Nav[i].icon,
            path: item.path,
            title: item.meta.title,
            closable: item.meta.closable,
            sort: item.meta.sort,
          });
        }
      }
    });
    // const Home = Menus[0];//首页
    // Home.closable = false;//禁止关闭首页
    // Nav.forEach(item => {
    //   const index = Parent.indexOf(item.id);
    //   if (index > -1) {
    //     Menus.push(item)
    //   }
    // });
    // const data = JSON.parse(JSON.stringify(Menus));
    // const list = filter(data, data.filter(v => v.parentId === 0).sort(compare('sort')));//过滤好后的左侧权限
    // console.log(list)
    // commit('INIT_MENUS', {Path, Home, list});
    // resolve({Path, Home, list})
  })
}

//添加页签路由
export function addVisitedViews({commit}, view) {
  return commit('ADD_VISITED_VIEWS', view);//去触发ADD_VISITED_VIEWS，并传入参数
}

//关闭页签--删除路由数据的方法
export function delVisitedViews({commit, state}, view) {
  return new Promise((resolve) => {
    const list = JSON.parse(JSON.stringify(state.visitedviews));//上一次的页签集合
    commit('DEL_VISITED_VIEWS', view);
    resolve({visitedviews: [...state.visitedviews], view: list});//resolve方法：成功后回调的方法,返回新的state.visitedviews
  })
}

//匹配过滤路由
export const filterRouter = ({commit, state}, list) => {
  return new Promise((resolve) => {
    const parent = "/Index";
    const data = JSON.parse(JSON.stringify(list));
    const routes = Flatten(data, "children", true);
    const options = [];
    asyncRouterMap.forEach(item => {
      routes.forEach(self => {
        if (item.path === self.path) {
          const obj = {
            path: item.path,
            name: item.name,
            component: item.component,
            meta: {
              keepAlive: item.meta.keepAlive,
              closable: item.meta.closable,
              bar: item.meta.bar,
              title: self.title,
            },
          };
          options.push(obj);
        }
      });
    });
    const index = router.options.routes.map(v => v.path).indexOf(parent);
    if (index > -1) {
      router.matcher = new Router({mode: 'hash'}).matcher;
      router.options.routes[index].children = options;
      router.addRoutes(router.options.routes.concat([{//捕获未定义的路由配置
        path: '*',
        redirect: '/NotFound',
        hidden: true,
      }]));
      const home = !options || options === null || options.length === 0 ? {} : options[0];
      commit('FILTER_ROUTER', {list: home, type: 'home'});
      resolve(home);
    }
  });
};
//匹配过滤导航菜单
export const filterMenus = ({commit, state}, list) => {
  return new Promise((resolve) => {
    const routes = Flatten(JSON.parse(JSON.stringify(list)), "children", true);
    const data = Flatten(JSON.parse(JSON.stringify(state.menus)), "children", true);
    const path = data.map(v => v.path);
    const arr = [];
    routes.forEach(item => {
      const index = path.indexOf(item.path);
      if (index > -1) {
        const self = data[index];
        const obj = {
          icon: self.icon ? self.icon : "",
          name: self.title,
          path: self.path,
          sort: item.sort,
          id: item.id,
          parentId: item.parentId,
        };
        arr.push(obj);
      }
    });
    const parent = arr.filter(v => v.parentId === 0).sort(compare('sort'));
    const menus = recombineMenus(arr, parent);
    commit('FILTER_ROUTER', {list: menus, type: 'role'});
    resolve();
  });
};
//数组重组获取导航菜单
const recombineMenus = (data, list) => {
  list.forEach(item => {
    item.children = [];
    for (let j = 0; j < data.length; j++) {
      if (data[j].parentId === item.id) {
        item.children.push(data[j]);
      }
      else {
        if (item.children) {
          recombineMenus(data, item.children)
        }
      }
    }
    if (item.children.length === 0) {
      delete item.children;
    }
  });
  return list.sort(compare('sortId'));
};